package com.zhaotianhao.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class CookieUtils {
    //添加cookie
    public static void  addCookie(String name, String value, int time, HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(time);//设置时间
            cookie.setPath("/");//设置路径,同一服务器内所有应用都可访问到该Cookie
            response.addCookie(cookie);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //删除cookie
    public static void  removeCookie(String name,HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, "");
            cookie.setMaxAge(-1);//设置时间
            cookie.setPath("/");//设置路径,同一服务器内所有应用都可访问到该Cookie
            response.addCookie(cookie);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 清空所有cookie
     * @param request
     * @param response
     */
    public static void  removeAllCookie(HttpServletRequest request,HttpServletResponse response){
        try {
            Cookie[] cookies = request.getCookies();//获取所有的cookie
            if(null !=cookies && cookies.length>0){
                for (Cookie cookie : cookies) {
                    cookie.setMaxAge(-1);//设置时间
                    cookie.setPath("/");//设置路径,同一服务器内所有应用都可访问到该Cookie
                    response.addCookie(cookie);
                }
            }
           }catch (Exception e){
            e.printStackTrace();
        }
    }
}
